package com.doform.android.xianggucheng.activity.downorder;

import android.content.Intent;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.allinpay.usdk.core.data.ResponseData;
import com.doform.android.xianggucheng.IApplication;
import com.doform.android.xianggucheng.R;
import com.doform.android.xianggucheng.activity.BaseActivity;
import com.doform.android.xianggucheng.activity.BaseTitleActivity;
import com.doform.android.xianggucheng.activity.PayCompleteActivity;
import com.doform.android.xianggucheng.bean.QueryLibraryBean;
import com.doform.android.xianggucheng.bean.WorkerBean;
import com.doform.android.xianggucheng.bean.request_bean.ReqListLibraryBean;
import com.doform.android.xianggucheng.bean.request_bean.ReqUpdateOrder;
import com.doform.android.xianggucheng.popwindow.CommonDialog;
import com.doform.android.xianggucheng.popwindow.CommonPopWindow;
import com.doform.android.xianggucheng.retrofit.HttpManager;
import com.doform.android.xianggucheng.retrofit.subscriber.ErrorHandleSubscriber;
import com.doform.android.xianggucheng.utils.Constans;
import com.doform.android.xianggucheng.utils.TsUtils;
import com.doform.android.xianggucheng.widget.DividerItemDecoration;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

/**
 * Created by Administrator on 2017/5/10.
 */

public class CashActivity extends BaseTitleActivity {

    @BindView(R.id.btn_submit)
    Button mSubmit;

    @BindView(R.id.ll)
    LinearLayout mLl;

    @BindView(R.id.rl_pay)
    RelativeLayout mPay;

    @BindView(R.id.tv_order_id)
    TextView tv_order;

    @BindView(R.id.tv_price)
    TextView tv_price;

    @BindView(R.id.tv_pay)
    TextView tv_pay;

    @BindView(R.id.tv_persion)
    TextView tv_persion;

    @BindView(R.id.tv_library)
    TextView tv_library;

    @BindView(R.id.tv_sure_pay)
    EditText et_sure_pay;

    @BindView(R.id.rl_true_pay)
    RelativeLayout rl_true_pay;

    private String mID;
    private String mGUID;
    private String mSurePay;
    private String mWorkerId;
    private String mLibraryId;
    private String stringExtraPrice;
    private CommonDialog mPayPop;
    private CommonPopWindow mEmployeePop;
    private CommonPopWindow mLibraryPop;
    private CommonAdapter<WorkerBean> mEmCommonAdapter;
    private CommonAdapter<String> mPayCommonAdapter;
    private RecyclerView mLibRecyclerView;
    private RecyclerView mPayRecyclerView;
    private RecyclerView mEmRecyclverView;
    private List<WorkerBean> mEmDatas = new ArrayList<>();
    private List<QueryLibraryBean> mLibraryDatas = new ArrayList<>();


    /**
     * 支付方式
     */
    private String payStyle;

    private boolean havePoss = false;
    private CommonAdapter mLibrAdapter;
    private String mlibraryName;
    private String mWorkName;

    @Override
    protected int layoutResId() {
        return R.layout.activity_cash;
    }

    @Override
    protected void init() {

        initActivity();

        this.mID = getIntent().getStringExtra(Constans.EXTRA_CASH_ID);
        this.mGUID = getIntent().getStringExtra(Constans.EXTRA_CASH_GUID);
        this.stringExtraPrice = getIntent().getStringExtra(Constans.EXTRA_CASH_PRICE);

        mPayPop = new CommonDialog(this, R.layout.dialog_pay_recycler_item);
        mEmployeePop = new CommonPopWindow(this, R.layout.pop_recycler_item);
        mLibraryPop = new CommonPopWindow(this, R.layout.pop_recycler_item);
    }


    private List<String> mPayDatas = new ArrayList<>();

    @Override
    protected void initView() {
        mPayRecyclerView = mPayPop.getView(R.id.recyclerView);
        mPayRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mPayRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mPayRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));

        mEmRecyclverView = mEmployeePop.getView(R.id.recyclerView);
        mEmRecyclverView.setLayoutManager(new LinearLayoutManager(this));
        mEmRecyclverView.setItemAnimator(new DefaultItemAnimator());
        mEmRecyclverView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));


        mLibRecyclerView = mLibraryPop.getView(R.id.recyclerView);
        mLibRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mLibRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mLibRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));


    }


    @Override
    protected void initData() {

        mPayDatas.add("支付宝支付");
        mPayDatas.add("微信支付");
        mPayDatas.add("现金支付");
        mPayDatas.add("未付款");

        getPersonDataForService();
        getLibraryDataForService();
    }

    @Override
    protected void showView() {

        titleBar.setTextTitle("收银");
        tv_order.setText(mID);
        tv_price.setText(stringExtraPrice);
        tv_pay.setText("请选择支付方式");
        tv_persion.setText("请选择配送人员");
        et_sure_pay.setText(stringExtraPrice);
        et_sure_pay.requestFocus();

    }

    private void getLibraryDataForService() {
        HttpManager
                .instance()
                .getLibraryQuery(new ReqListLibraryBean())
                .subscribe(new ErrorHandleSubscriber<ArrayList<QueryLibraryBean>>() {
                               @Override
                               public void onNext(@NonNull ArrayList<QueryLibraryBean> queryLibraryBeen) {
                                   parseLibrary(queryLibraryBeen);
                               }
                           }
                );
    }

    private void parseLibrary(@NonNull ArrayList<QueryLibraryBean> queryLibraryBeen) {
        mLibraryDatas.clear();
        mLibraryDatas.addAll(queryLibraryBeen);
        mLibrAdapter.notifyDataSetChanged();
        if (mLibraryDatas.size() == 1) {
            mLibraryId = mLibraryDatas.get(0).getId();
            mlibraryName = mLibraryDatas.get(0).getName();
        }
        tv_library.setText(mlibraryName);
    }

    private void getPersonDataForService() {
        HttpManager.instance()
                .getWorker()
                .subscribe(new ErrorHandleSubscriber<ArrayList<WorkerBean>>() {
                    @Override
                    public void onNext(@NonNull ArrayList<WorkerBean> data) {
                        parseEmployeeData(data);
                    }
                });
    }


    private void parseEmployeeData(List<WorkerBean> mess) {
        mEmDatas.clear();
        mEmDatas.addAll(mess);
        mEmCommonAdapter.notifyDataSetChanged();
    }

    @Override
    protected void initListener() {

        mEmCommonAdapter = new CommonAdapter<WorkerBean>(this, R.layout.pop_category_item2, mEmDatas) {
            @Override
            protected void convert(ViewHolder holder, WorkerBean messBean, int position) {
                TextView tv = holder.getView(R.id.tv);
                tv.setText(messBean.getEname());
            }
        };

        mEmCommonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {

                WorkerBean messBean = mEmDatas.get(position);
                mWorkerId = messBean.getId();
                mWorkName = messBean.getEname();
                tv_persion.setText(messBean.getEname());
                mEmployeePop.dismiss();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;

            }
        });

        mEmRecyclverView.setAdapter(mEmCommonAdapter);


        mLibrAdapter = new CommonAdapter<QueryLibraryBean>(this, R.layout.pop_category_item2, mLibraryDatas) {
            @Override
            protected void convert(ViewHolder holder, QueryLibraryBean messBean, int position) {
                TextView tv = holder.getView(R.id.tv);
                tv.setText(messBean.getName());
            }
        };

        mLibrAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {

                QueryLibraryBean messBean = mLibraryDatas.get(position);
                mLibraryId = messBean.getId();
                mlibraryName = messBean.getName();
                tv_library.setText(messBean.getName());
                mLibraryPop.dismiss();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;

            }
        });

        mLibRecyclerView.setAdapter(mLibrAdapter);


        mPayCommonAdapter = new CommonAdapter<String>(this, R.layout.pop_category_item2, mPayDatas) {
            @Override
            protected void convert(ViewHolder holder, String messBean, int position) {
                TextView tv = holder.getView(R.id.tv);
                tv.setText(messBean);
            }
        };
        mPayCommonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                String pay = mPayDatas.get(position);
                tv_pay.setText(pay);

                switch (pay) {
//                    {0：未付款,1：现金,2：刷卡,3:微信,4:支付宝}
                    case "支付宝支付":
                        payStyle = "3";
                        break;
                    case "微信支付":
                        payStyle = "2";
                        break;
                    case "现金支付":
                        payStyle = "1";
                        break;
                    case "未付款":
                        payStyle = "0";
                        break;
                }
                mPayPop.dismiss();
            }


            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        mPayRecyclerView.setAdapter(mPayCommonAdapter);
    }


    private void beforeSubmit() {

        if (TextUtils.isEmpty(payStyle)) {
            TsUtils.showToast("请选择支付方式");
            return;
        } else if (TextUtils.isEmpty(mWorkerId)) {
            mWorkerId = "";
        } else if (TextUtils.isEmpty(mLibraryId)) {
            TsUtils.showToast("请选择出货仓库");
            return;
        }

        pay(payStyle);
    }

    //    点击提交 执行支付流程
    private void pay(String payStyle) {
//        {0：未付款,1：现金,3:微信,4:支付宝}
        switch (payStyle) {
            case "3":
            case "2":
                beforeCode();//扫码支付
                break;
            case "1":
                postDataToService("1");
                break;
            case "0":
                postDataToService("0");
                break;
            default:
                break;
        }

    }

    private void postDataToService(String payStyle) {

        mSurePay = et_sure_pay.getText().toString().trim();

        submit(mID, mGUID, "4", mLibraryId, mlibraryName, mWorkerId, mWorkName, payStyle, mSurePay);
    }

    private void submit(String mID, String mGUID, String state, String mLibraryId, String mlibraryName, String mWorkerId, String mWorkName, String payStyle, String mSurePay) {

        HttpManager
                .instance()
                .updateOrder(new ReqUpdateOrder(mID, mGUID, state, mLibraryId, mlibraryName, mWorkerId, mWorkName, payStyle, mSurePay))
                .subscribe(new ErrorHandleSubscriber<Integer>() {
                               @Override
                               public void onNext(@NonNull Integer s) {
                                   Intent intent = new Intent(CashActivity.this, OrderQueryActivity.class);
                                   intent.putExtra(Constans.EXTRA_ORDER_QUERY, "4");
                                   startActivity(intent);
                                   finish();
                               }
                           }
                );
    }


    private void beforeCode() {
        goCodePay(mID);
    }

    /**
     * 二维码支付
     */
    private void goCodePay(String id) {

        Intent intent = new Intent(this,PayActivity.class);
        intent.putExtra(Constans.EXTRA_PAY_CODE,id);
        startActivityForResult(intent,Constans.REQUEST_PAY);

    }

    private void postDataToService(ResponseData respone) {

        mSurePay = et_sure_pay.getText().toString().trim();

        if (payStyle == "" || payStyle == null || TextUtils.isEmpty(payStyle)) {
            Toast.makeText(this, "请选择支付方式", Toast.LENGTH_SHORT).show();
            return;
        }
        submit(payStyle, mSurePay, mWorkerId, respone);
    }

    private void submit(String payType, String surePay, String mEmployeeId, final ResponseData respone) {
        Intent intent = new Intent(CashActivity.this, PayCompleteActivity.class);
        intent.putExtra(Constans.EXTRA_PAY_COMPLETE, respone);
        startActivity(intent);
        finish();
    }

    private void initActivity() {

        List<BaseActivity> activities = IApplication.getInstance().getActivities();
        for (int i = 0; i < activities.size(); i++) {
            BaseActivity activity = activities.get(i);
            if ("activity.MainActivity".equals(activity.getLocalClassName())) {
            } else if ("activity.downorder.CashActivity".equals(activity.getLocalClassName())) {
            } else {
                activity.finish();
            }
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            //do something...
            Intent intent = new Intent(this, OrderQueryActivity.class);
            intent.putExtra(Constans.EXTRA_ORDER_QUERY, "1");
            startActivity(intent);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @OnClick({R.id.btn_submit, R.id.rl_pay, R.id.tv_persion, R.id.tv_library})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.btn_submit:
                beforeSubmit();
                break;
            case R.id.rl_pay:
                mPayPop.show();
                break;
            case R.id.tv_persion:
                mEmployeePop.showAtLocation(mLl, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.tv_library:
                mLibraryPop.showAtLocation(mLl, Gravity.BOTTOM, 0, 0);
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_back:
                Intent intent = new Intent(CashActivity.this, OrderQueryActivity.class);
                intent.putExtra(Constans.EXTRA_ORDER_QUERY, "1");
                startActivity(intent);
                finish();
                break;
            default:
                break;
        }


    }
}
